<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['web:base:profile:tbCommonApply:add']"
        >
          新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      tooltip-effect
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="申请用户" align="center" prop="initiatorName" />
      <el-table-column label="申请事由" align="center" prop="reason" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button
            v-if="['制单', '已撤销', '审批退回'].includes(row.status)"
            link
            type="success"
            icon="Position"
            @click="handleSubmit(row)"
          >
            提交
          </el-button>
          <el-button
            link
            type="primary"
            icon="Document"
            @click="handleDetail(row)"
            v-hasPermi="['web:base:profile:tbCommonApply:info']"
          >
            详情
          </el-button>
          <el-button
            v-if="['制单', '已撤销', '审批退回'].includes(row.status)"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(row)"
            v-hasPermi="['web:base:profile:tbCommonApply:edit']"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      v-model="open"
      :title="title"
      width="500px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="code">
          <el-input v-model="form.code" placeholder="自动生成" disabled />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="deptOptions.filter((f) => f.status === '0')"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="id"
            placeholder="选择所申请部门"
            check-strictly
            :disabled="title === '查看表单'"
          />
        </el-form-item>
        <el-form-item label="申请事由" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="5"
            maxlength="250"
            show-word-limit
            placeholder="请输入申请事由"
            :disabled="title === '查看表单'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div v-if="title !== '查看表单'" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="success" @click="handleInitiateProcess">提 交</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <FormDetail v-model="detailVisible" :form-data="form" :log-list="logList" :is-detail="true" />
  </div>
</template>

<script setup>
  import { ref, getCurrentInstance, onMounted } from 'vue';
  import { useRoute } from 'vue-router';
  import modal from '@/plugins/modal';
  import { listDept } from '@/api/system/dept';
  import {
    addListForm,
    editListForm,
    initiateProcess,
    listForm,
    listFormInfo,
    submitListForm,
  } from '@/api/flowable/form-list';
  import useUserStore from '@/store/modules/user';
  import FormDetail from '@/views/flowable/form-list/component/form-detail.vue';
  import { approvalLog } from '@/api/flowable/process-center';
  import { ElMessageBox } from 'element-plus';

  const { proxy } = getCurrentInstance();
  const userStore = useUserStore();
  const route = useRoute();
  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({
    code: null,
  });
  const queryRef = ref(null);
  const list = ref([]);
  const open = ref(false);
  const loading = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');
  const formRef = ref(null);
  const form = ref({});
  const rules = ref({
    deptId: [{ required: true, message: '所属部门不能为空', trigger: 'blur' }],
    reason: [{ required: true, message: '申请事由不能为空', trigger: 'blur' }],
  });
  const deptOptions = ref([]);
  const detailVisible = ref(false);
  const logList = ref([]);

  async function getList() {
    loading.value = true;
    const res = await listForm(pageParams.value, queryParams.value);
    list.value = res?.data?.records ?? [];
    total.value = res?.data?.total ?? 0;
    loading.value = false;
  }

  function cancel() {
    open.value = false;
    reset();
  }

  function reset() {
    form.value = {
      code: null,
      deptId: null,
      reason: null,
      initiatorId: null,
    };
    formRef.value?.resetFields();
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }

  function handleAdd() {
    reset();
    title.value = '添加表单';
    open.value = true;
  }

  async function handleUpdate(row) {
    reset();
    const _id = row?.id ?? ids.value[0];
    const res = await listFormInfo(_id);
    form.value = res.data;
    title.value = '修改表单';
    open.value = true;
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        form.value.initiatorId = userStore.id;
        if (form.value.id) {
          editListForm(form.value).then(() => {
            modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addListForm(form.value).then(() => {
            modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  function handleInitiateProcess() {
    formRef.value.validate((valid) => {
      if (valid) {
        ElMessageBox.confirm('确定发起流程吗', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            form.value.initiatorId = userStore.id;
            submitListForm(form.value).then((res) => {
              open.value = false;
              if (res.msg.indexOf('失败') !== -1) {
                modal.msgWarning(res.msg);
              } else {
                modal.msgSuccess(res.msg);
              }
              getList();
            });
          })
          .catch((e) => {
            console.log(e);
          });
      }
    });
  }

  function handleSubmit(row) {
    modal
      .confirm('是否确认发起流程？')
      .then(() => {
        return initiateProcess({ businessId: row.id, businessType: 'commonApply' }); // businessType为对应的表单类型
      })
      .then(() => {
        getList();
        modal.msgSuccess('操作成功');
      })
      .catch(() => {});
  }

  async function handleDetail(row) {
    const res = await listFormInfo(row.id);
    form.value = res.data;
    await getLogList(row.processInstanceId);
    detailVisible.value = true;
  }

  async function getLogList(id) {
    const res = await approvalLog(id);
    logList.value = res?.data?.records ?? [];
  }

  async function getFormDeptOptions() {
    const res = await listDept();
    deptOptions.value = proxy.handleTree(res.data, 'deptId');
  }

  onMounted(async () => {
    await getList();
    if (route.query.id) {
      const res = await listForm({ pageNum: 1, pageSize: 999 }, { id: route.query.id });
      const info = res?.data?.records.find((f) => f.id === Number(route.query.id));
      await handleUpdate(info);
    }
  });

  getList();
  getFormDeptOptions();
</script>
